package com.eascs.admin.o2o.backfee.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.admin.o2o.backfee.entity.*;
import com.eascs.admin.o2o.backfee.form.ComBackFeeForm;
import com.eascs.admin.o2o.backfee.form.ComBackReceiveByOldForm;
import com.eascs.admin.o2o.backfee.form.ComBackReceiveForm;
import com.eascs.admin.o2o.backfee.service.O2OComBankFeeService;
import com.eascs.admin.o2o.backfee.trans.O2oComBackFeeTransFormart;
import com.eascs.admin.o2o.backfee.trans.OaBackFeeTransO2Oloanapply;
import com.eascs.admin.o2o.internal.entity.LoanapplyExpand;
import com.eascs.admin.o2o.internal.service.LoanapplyExpandService;
import com.eascs.admin.o2o.internal.util.BaseUtils;
import com.eascs.admin.o2o.internal.util.StatusContexts;
import com.eascs.admin.o2o.loan.entity.O2oLoanUserEntity;
import com.eascs.admin.o2o.loan.entity.O2oLoanapplyEntity;
import com.eascs.admin.o2o.loan.service.O2oLoanUserService;
import com.eascs.admin.o2o.loan.service.O2oLoanapplyService;
import com.eascs.admin.o2o.loan.utils.BankNoCheckUtil;
import com.eascs.admin.o2o.loanAccount.entity.O2oLoanapplyAccountEntity;
import com.eascs.admin.o2o.loanAccount.service.Io2oLoanapplyAccountService;
import com.eascs.app.dao.PageResult;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.util.DateUtils;
import com.eascs.common.util.StringUtil;
import com.eascs.common.util.UrlUtil;
import com.eascs.crm.common.service.ICustomerInfoService;
import com.eascs.crm.common.vo.CustomerView;
import com.eascs.crm.common.vo.QueryCustomerVO;
import com.eascs.loan.vo.O2oRepaymentRecordVo;
import com.eascs.site.controller.BaseRestController;
import com.eascs.site.page.PaginationInfo;
import com.eascs.site.page.SelectDataOption;
import com.eascs.site.view.BaseRestResult;
import com.eascs.site.view.HtmlRestResult;
import com.eascs.site.view.PaginationRestResult;
import com.eascs.site.view.ViewContext;
import com.eascs.site.view.button.Button;
import com.eascs.site.view.button.ButtonHelper;
import com.eascs.site.view.button.ShowButtonFilter;
import com.eascs.web.context.RequestContext;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;
import com.eascs.workflow.common.entity.wf.ProcessTemplate;
import com.eascs.workflow.common.service.sys.SysOrgService;
import com.eascs.workflow.common.type.SystemModule;
import com.eascs.workflow.common.vo.ModelResult;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/rbackfee")
public class O2oComBackFeeRestController extends BaseRestController {
	private static Logger logger = LoggerFactory.getLogger(O2oComBackFeeRestController.class);
	@Autowired
	O2OComBankFeeService o2oComBankFeeService;
	@Autowired
	private O2oLoanapplyService o2oLoanapplyService;
	@Reference
	ICustomerInfoService iCustomerInfoService;
	@Autowired
	private LoanapplyExpandService loanapplyExpandService;
	@Autowired
	private BaseUtils baseUtils;
	@Autowired
	private O2oLoanUserService o2oLoanUserService;

	@Reference
	SysOrgService sysOrgService;
	
	@Autowired
	Io2oLoanapplyAccountService o2oLoanapplyAccountService;
	
	private static Logger log = LoggerFactory.getLogger(O2oComBackFeeRestController.class);

	@RequestMapping("/oabackfee")
	public PaginationRestResult getOaBasicData(FormBackFeeEntity entity) {
		// @o2o
		entity.setPageSize(10);
		// @OA
		PageResult<Object[]> oapageResult = o2oComBankFeeService.findOaByPage(entity);
		String[] oatitles = { "内审单号", "借款人姓名", "申请状态", "已收保证金(元)", "已退保证金(元)", "未退保证金(元)", "已收管理费(元)", "已退管理费(元)", "未退管理费(元)", "已收风险补偿金(元)", "已退风险补偿金(元)", "未退风险补偿金(元)", "信贷经理", "实际到帐时间" };
		//String oapageUrl = "/rbackfee/oabackfee";
		SelectDataOption[] selectDataOptions = {null, null, new SelectDataOption("SQZT","ALL"), null, null, null, null, null, null, null, null, null, null, null};
		PaginationInfo oapaginationInfo = new PaginationInfo(oapageResult, oatitles, UrlUtil.resetParam(RequestContext.getRequestUrlWithQueryString(), "showOaPage", ""));
		oapaginationInfo.setBuildPagingNavigation(true);
		oapaginationInfo.setFirstRenderColumnIndex(0);
		Button[] oafindButton = new Button[] { ButtonHelper.createAjaxButton(null, "/rbackfee/oadetail?billCode="), null };
		Button shenqign = ButtonHelper.createAjaxButton("申请退费", "/rbackfee/edit_oabond?billCode=");
		Button gatherPrint = ButtonHelper.createAjaxButton("打印收款收据", "/rbackfee/gatherPrintByOld?billCode=");
		gatherPrint.setPermissionCode("gatherPrint");
		Button[] findButton = new Button[] { shenqign,gatherPrint };
		oapaginationInfo.setSelectDataOptions(selectDataOptions);
		oapaginationInfo.setTitleButtons(oafindButton);
		oapaginationInfo.setMoreButtons(findButton);
		oapaginationInfo.setFormats(new Format[] { null, null, null, new DecimalFormat(",##0.00"), new DecimalFormat(",##0.00"), new DecimalFormat(",##0.00"), new DecimalFormat(",##0.00"), new DecimalFormat(",##0.00"), new DecimalFormat(",##0.00"), new DecimalFormat(",##0.00"), new DecimalFormat(",##0.00"), new DecimalFormat(",##0.00"), null, null });
		oapaginationInfo.setRendTo("#oa_result");
		ViewContext.put("vo", entity);
		return PaginationRestResult.buildPaginationRestResult(oapaginationInfo);
	}

	@SuppressWarnings("unused")
	@RequestMapping("/o2obackfee")
	public PaginationRestResult getO2oBasicData(FormBackFeeEntity entity) {
		// @o2o
		entity.setPageSize(10);
		
		List<User> users=sysOrgService.checkDataPermission(UserHolder.getUser().getNo());
		String no="";
		if (users!=null) {
			for (User user : users) {
				no+=user.getNo()+",";
			}
		}
		if (!"".equals(no)) {
			if (",".equals(no.substring(no.length()-1, no.length()))) {
				no=no.substring(0, no.length()-1);
			}
		}
		logger.info("userno={}", no);
		entity.setXdjlNo(no);
		
		
		PageResult<Object[]> o2opageResult = o2oComBankFeeService.findByPage(entity);
		String[] o2otitles = { "内审单号", "借款人姓名", "申请状态", "已收保证金(元)", "已退保证金(元)", "未退保证金(元)", "已收管理费(元)", "已退管理费(元)", "未退管理费(元)", "已收风险补偿金(元)", "已退风险补偿金(元)", "未退风险补偿金(元)", "实际到帐时间", "缴纳状态" };
		String o2opageUrl = "/rbackfee/o2obackfee";
		if (entity != null) {
			String billCode = entity.getBill_code() == null ? "" : entity.getBill_code();
			String userName = entity.getName() == null ? "" : entity.getName();
			String payMentStatus = entity.getPayMentStatus() == null ? "" : entity.getPayMentStatus();
			o2opageUrl = UrlUtil.appendUrl(o2opageUrl, "bill_code", billCode);
			o2opageUrl = UrlUtil.appendUrl(o2opageUrl, "name", userName);
			o2opageUrl = UrlUtil.appendUrl(o2opageUrl, "payMentStatus", payMentStatus);
			o2opageUrl = o2opageUrl + "&showO2oPage=";
		} else {
			o2opageUrl = o2opageUrl + "?showO2oPage=";
		}
		SelectDataOption[] selectDataOptions = {null, null, new SelectDataOption("SQZT","ALL"), null, null, null, null, null, null, null, null, null, null, new SelectDataOption("OTO_BZJ_GLF")};
		PaginationInfo paginationInfo = new PaginationInfo(o2opageResult, o2otitles, o2opageUrl);
		paginationInfo.setBuildPagingNavigation(true);
		paginationInfo.setFirstRenderColumnIndex(0);
		paginationInfo.setSelectDataOptions(selectDataOptions);
//		Button shenqign = ButtonHelper.createAjaxButton("申请退费", "/rbackfee/o2o_edit_oabond?billCode=");
//		Button gatherPrint = ButtonHelper.createAjaxButton("打印收款收据", "/rbackfee/gatherPrint?printType=NEW&billCode=");
//		shenqign.setShowButtonFilter(showBottun);
//		shenqign.setPermissionCode("refundApply");
//		gatherPrint.setPermissionCode("gatherPrint");
//		Button[] findButton = new Button[] { shenqign,gatherPrint };
		Button detail = ButtonHelper.createAjaxButton(null, "/rbackfee/detail?billCode=");
		Button[]  titleButtons= new Button[] { detail};
		paginationInfo.setFormats(new Format[] { null, null, null, new DecimalFormat(",##0.00"), new DecimalFormat(",##0.00"), new DecimalFormat(",##0.00"), new DecimalFormat(",##0.00"), new DecimalFormat(",##0.00"), new DecimalFormat(",##0.00"), new DecimalFormat(",##0.00"), new DecimalFormat(",##0.00"), new DecimalFormat(",##0.00"), null, null });
//		paginationInfo.setMoreButtons(findButton);
		paginationInfo.setTitleButtons(titleButtons);
		paginationInfo.setRendTo("#o2o_result");
		ViewContext.put("vo", entity);
		return PaginationRestResult.buildPaginationRestResult(paginationInfo);
	}
	
	/**
	 * 是否显示申请退费按钮过滤器
	 */
	public ShowButtonFilter showBottun = new ShowButtonFilter() {
		
		@Override
		public boolean filter(Object param) {
			Object[] params = (Object[]) param;
			if (params[12].equals(StatusContexts.O2O_BANK_CLO)) {
				if(params[4].toString().equals("0.0000")&&params[7].toString().equals("0.0000")&&params[10].toString().equals("0.0000")){
					return false;
				}else{
					return true;
				}
			} else {
				return false;
			}
		}
	};
	
	/**
	 * @Description: <p> 保证金详情页面 </p>
	 * @author CXW
	 * @date 2016年9月22日 上午10:44:59
	 * @version V1.0
	 * @param 
	 * @return BaseRestResult<String>
	 */
	@RequestMapping("/detail")
	public BaseRestResult<String> detail(String billCode){
		O2oLoanapplyEntity loan = o2oLoanapplyService.fingByBillCode(billCode);
//		LoanapplyExpand loanapplyExpand = loanapplyExpandService.queryLoanapplyNo(loan.getLoanapplyNo());
//		O2oLoanUserEntity loanUser = o2oLoanUserService.findById(loan.getLoanId(), loan.getLoanapplyNo());
//		FormBackFeeEntity entity = new FormBackFeeEntity();
//		entity.setPageSize(Integer.MAX_VALUE);
//		entity.setBill_code(billCode);
//		PageResult<Object[]> pageResult = o2oComBankFeeService.findByPageList(entity);
//		SelectDataOption[] selectDataOptions = { null,  null, null, null, null, null,null,null,new SelectDataOption("BILLSTATUS") };
//		String[] titles = { "单据号", "借款人姓名", "退费开户银行名称", "退费银行账", "退费账户户名", "退风险补偿金金额", "退管理费金额", "退保证金金额", "状态" };
//		PaginationInfo paginationInfo = new PaginationInfo(pageResult, titles);
//		paginationInfo.setBuildPagingNavigation(true);
//		paginationInfo.setFirstRenderColumnIndex(1);
//		paginationInfo.setSelectDataOptions(selectDataOptions);
//		paginationInfo.setFormats(new Format[] { null, null,null,null,null, new DecimalFormat(",##0.00"),new DecimalFormat(",##0.00"), new DecimalFormat(",##0.00"), null });
//		loanapplyExpand =o2oComBankFeeService.sumn(loanapplyExpand);
//		ViewContext.put("paginationInfo", paginationInfo);
		ViewContext.put("loanapply", loan);
//		ViewContext.put("loanapplyExpand", loanapplyExpand);
//		ViewContext.put("loanUser", loanUser);
		String agreeUrl = baseUtils.getApprovalAgreeUrl(loan.getLoanapplyNo(), null, SystemModule.SYSTEM_MODULE_O2O);
		ViewContext.put("agreeUrl", agreeUrl);
		O2oLoanapplyAccountEntity loanapplyAccountEntity = o2oLoanapplyAccountService.getEntityByLoanapplyNo(loan.getLoanapplyNo());
		if (loanapplyAccountEntity != null) {
			ViewContext.put("accountId", loanapplyAccountEntity.getAccountNo());
		}
		return HtmlRestResult.popHtmlFragment("backfee/backfee_detail");
	}

	/**
	 * oa提交退费流程页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/edit_oabond")
	public HtmlRestResult loanfile(String billCode) {
		OaBackFeeEntity oaBackFeeEntity = getOaBackFeeEntity(billCode);
		Button button = ButtonHelper.createAjaxButton("启动流程", "/rbackfee/oastartup?billCode=" + billCode);
		ViewContext.put("button", button);
		ViewContext.put("vo", trans(billCode));
		ViewContext.put("backfee", oaBackFeeEntity);
		ViewContext.put("oaStatus", getStringOaStatus(billCode));
		
		O2OComBackFee o2OComBackFee = o2oComBankFeeService.queryEntity(oaBackFeeEntity.getLoanapplyno(), StatusContexts.WFTYPE_STATUS_NEW);
		ViewContext.put("comBackFeeForm", o2OComBackFee);
		//退费信息
		backeFeeList(billCode);
		return HtmlRestResult.popHtmlFragment("backfee/oa_update_bond");
	}
	
	
	public void backeFeeList(String billCode){
		FormBackFeeEntity entity = new FormBackFeeEntity();
		entity.setPageSize(10);
		entity.setBill_code(billCode);
		String url = "/backfee/list";
		url = UrlUtil.appendUrl(url, "billCode", billCode);
		PageResult<Object[]> pageResult = o2oComBankFeeService.findByPageList(entity);
		SelectDataOption[] selectDataOptions = { null,  null, null, null, null, null,null,null,new SelectDataOption("BILLSTATUS") };
		String[] titles = { "单据号", "借款人姓名", "退费开户银行名称", "退费银行账", "退费账户户名", "退风险补偿金金额", "退管理费金额", "退保证金金额", "状态" };
		PaginationInfo paginationInfo = new PaginationInfo(pageResult, titles, url);
		paginationInfo.setBuildPagingNavigation(true);
		paginationInfo.setFirstRenderColumnIndex(1);
		paginationInfo.setSelectDataOptions(selectDataOptions);
		paginationInfo.setFormats(new Format[] { null, null,null,null,null, new DecimalFormat(",##0.00"),new DecimalFormat(",##0.00"), new DecimalFormat(",##0.00"), null });
		ViewContext.put("paginationInfo", paginationInfo);
		ViewContext.put("paginationInfo", paginationInfo);
	}
	/**
	 * oa退详细界面
	 * 
	 * @return
	 */
	@RequestMapping("/oadetail")
	public BaseRestResult<String> oadetail(String billCode){
		OaBackFeeEntity oaBackFeeEntity = getOaBackFeeEntity(billCode);
		O2oLoanapplyEntity loanapply = OaBackFeeTransO2Oloanapply.transO2oLoanapplyEntity(oaBackFeeEntity);
		Button button = ButtonHelper.createAjaxButton("启动流程", "/rbackfee/oastartup?billCode=" + billCode);
		ViewContext.put("button", button);
		ViewContext.put("vo", trans(billCode));
		ViewContext.put("backfee", oaBackFeeEntity);
		ViewContext.put("loanapply", loanapply);
		ViewContext.put("oaStatus", getStringOaStatus(billCode));
		backeFeeList(billCode);
		String agreeUrl = baseUtils.getApprovalAgreeUrl(oaBackFeeEntity.getLoanapplyno(), null, SystemModule.SYSTEM_MODULE_O2O);
		ViewContext.put("agreeUrl", agreeUrl);
		return HtmlRestResult.popHtmlFragment("backfee/oa_backfee_detail");
	}


	/**
	 * 启动流程按钮
	 * 
	 * @param billCode
	 * @return
	 */
	@RequestMapping(value = "/startbutton")
	public HtmlRestResult getStartButton(String billCode) {
		Button button = ButtonHelper.createAjaxButton("启动流程", "/rbackfee/oastartup?billCode=" + billCode);
		ViewContext.put("button", button);
		return HtmlRestResult.popHtmlFragment("backfee/bond_button");
	}

	/**
	 * 查询OA系统退费信息
	 * 
	 * @param billCode
	 * @return
	 */
	public ComBackFeeForm trans(String billCode) {
		OaUpdateBackFeeEntity oaUpdateBack = o2oComBankFeeService.findOaById(billCode);
		ComBackFeeForm comBackFeeForm = new ComBackFeeForm();
		comBackFeeForm.setLoanapplyNo(oaUpdateBack.getBillCode());
		comBackFeeForm.setBackDeposite(oaUpdateBack.getUnDeposit());
		comBackFeeForm.setBackManger(oaUpdateBack.getBackManger());
		comBackFeeForm.setBackRisk(oaUpdateBack.getBackRisk());
		comBackFeeForm.setBankAccount(oaUpdateBack.getBackBankAccount());
		comBackFeeForm.setBankAddr(oaUpdateBack.getBackBankAddr());
		comBackFeeForm.setBankName(oaUpdateBack.getBackBankName());
		comBackFeeForm.setPayType(oaUpdateBack.getBackPayType());
		comBackFeeForm.setPayMode(oaUpdateBack.getBackPayMode());
		comBackFeeForm.setPayRemark(oaUpdateBack.getBackPayRemark());
		if (null != oaUpdateBack.getBackPayDate())
			comBackFeeForm.setRequiredDate(DateUtils.formateStandTime(oaUpdateBack.getBackPayDate()));
		return comBackFeeForm;
	}

	/**
	 * 获取OA退费基本信息
	 * 
	 * @param billCode
	 * @return
	 */
	public OaBackFeeEntity getOaBackFeeEntity(String billCode) {
		return o2oComBankFeeService.findOaBackFee(billCode);
	}

	/**
	 * 获取OA系统退款数据流程状态
	 * 
	 * @param billCode
	 * @return
	 */
	public String getStringOaStatus(String billCode) {
		String sql = "SELECT OL.BILLSTATUSOTF FROM  EADB.O2O_LOANAPPLY OL WHERE OL.BILLCODE = ?";
		return o2oComBankFeeService.findString(sql, billCode);
	}

	/**
	 * o2o提交退费流程页面
	 * 
	 * @return
	 */
	@SuppressWarnings("unused")
	@RequestMapping(value = "/o2o_edit_oabond")
	public BaseRestResult<String> o2oloanfile(String billCode) {
		
		// 退费详细信息
		O2oLoanapplyEntity loanapply = o2oLoanapplyService.fingByBillCode(billCode);
		LoanapplyExpand loanapplyExpand = loanapplyExpandService.queryLoanapplyNo(loanapply.getLoanapplyNo());
		if (loanapplyExpand.getBillStatus().equals(StatusContexts.WFTYPE_STATUS_CLO)) {

			
			QueryCustomerVO vo = new QueryCustomerVO();
			vo.setCustomer_id(loanapply.getLoanId());
		/*	Button button = ButtonHelper.createAjaxButton("启动流程", "/combackfeesubmit/backfeestartup?billCode=" + billCode);
			ViewContext.put("button", button);*/
			CustomerView customer = iCustomerInfoService.geCustomerView(vo);

			O2OComBackFee o2OComBackFee = o2oComBankFeeService.queryEntity(loanapply.getLoanapplyNo(), StatusContexts.WFTYPE_STATUS_NEW);
			// 中间信息
			
			
			List<O2OComBackFee> o2OComBackFeelist = o2oComBankFeeService.findEntitys(loanapply.getBillCode());
			ViewContext.put("o2OComBackFeelist", o2OComBackFeelist);
			FormBackFeeEntity entity = new FormBackFeeEntity();
			entity.setPageSize(10);
			entity.setBill_code(billCode);
			String url = "/backfee/list";
			if (null != entity) {
				 billCode = entity.getBill_code() == null ? "" : entity.getBill_code();
				url = UrlUtil.appendUrl(url, "billCode", billCode);
				url = url + "&pageIndex=";
			} else {
				url = url + "?pageIndex=";
			}
			PageResult<Object[]> pageResult = o2oComBankFeeService.findByPageList(entity);
			SelectDataOption[] selectDataOptions = { null, null, null, null, null, null,null,null,new SelectDataOption("BILLSTATUS") };
			String[] titles = { "单据号", "借款人姓名", "退费开户银行名称", "退费银行账", "退费账户户名", "退风险补偿金金额", "退管理费金额", "退保证金金额", "状态" };
			PaginationInfo paginationInfo = new PaginationInfo(pageResult, titles, url);
			paginationInfo.setBuildPagingNavigation(true);
			paginationInfo.setFirstRenderColumnIndex(1);
			paginationInfo.setSelectDataOptions(selectDataOptions);
			paginationInfo.setFormats(new Format[] { null, null,null,null,null, new DecimalFormat(",##0.00"),new DecimalFormat(",##0.00"), new DecimalFormat(",##0.00"), null });
			ViewContext.put("paginationInfo", paginationInfo);
			loanapplyExpand =o2oComBankFeeService.sumn(loanapplyExpand);
			ViewContext.put("comBackFeeForm", o2OComBackFee);
			ViewContext.put("loanapply", loanapply);
			ViewContext.put("loanapplyExpand", loanapplyExpand);
			ViewContext.put("basic", customer.getBasicInfo());
			return HtmlRestResult.popHtmlFragment("backfee/o2o_update_bond");
		} else if (loanapplyExpand.getBillStatus().equals(StatusContexts.BZJ_STATUS_NEW)) {
			return BaseRestResult.warn("未缴纳保证金管理费。");
		} else {
			return BaseRestResult.warn("保证金管理费流程还未结束，无法退费。");
		}
	}

	/**
	 * check OA update
	 * 
	 *            退费类型
	 * @return
	 */
	@RequestMapping(value = "/oa_check")
	public BaseRestResult<String> oaCheck(String billCode) {
		int i = o2oComBankFeeService.findOaBackFeeCount(billCode);
		if (i == OaBackFeeStatus.BACK_COUNT) {// 保证金流程
			return BaseRestResult.warn("存在保证金退费流程");
		} else if (i == OaBackFeeStatus.MANA_COUNT) {// 管理费流程
			return BaseRestResult.warn("存在管理费退费流程");
		} else if (i == OaBackFeeStatus.RISK_COUNT) {// 风险补偿金流程
			return BaseRestResult.warn("存在风险补偿金退费流程");
		} else {// 可以退费
			return BaseRestResult.warn("");
		}
	}

	/**
	 * OA 启动退费流程
	 * 
	 * @param billCode
	 * @return
	 */
	@RequestMapping(value = "/oastartup")
	public BaseRestResult<String> oaStartUp(String billCode) {
		boolean isNull = trans(billCode) == null;
		boolean isNull1 = StringUtil.isEmpty(trans(billCode).getBackManger());
		boolean isNull2 = StringUtil.isEmpty(trans(billCode).getBackDeposite());
		boolean isNull3 = StringUtil.isEmpty(trans(billCode).getBackRisk());
		boolean isNull4 = StringUtil.isEmpty(trans(billCode).getPayRemark());
		boolean isNull5 = StringUtil.isEmpty(trans(billCode).getPayMode());
		boolean isNull6 = StringUtil.isEmpty(trans(billCode).getPayType());
		boolean isNull7 = StringUtil.isEmpty(trans(billCode).getBankAccount());
		boolean isNull8 = StringUtil.isEmpty(trans(billCode).getBankAddr());
		boolean isNull9 = StringUtil.isEmpty(trans(billCode).getBankName());
		boolean is = isNull || isNull1 || isNull2 || isNull3 || isNull4 || isNull5 || isNull6 || isNull7 || isNull8 || isNull9;
		if (is) {
			return BaseRestResult.warn("请先填写数据并保存");
		}
		O2oLoanapplyEntity loan = getOaLoanEntity(billCode);
		logger.debug("start-up Technological process params loanaopplyNo:{},billCode:{},OperatorNo:{},OperatorName:{},Ltd:{}", loan.getLoanapplyNo(), loan.getBillCode(), loan.getOperatorNo(), loan.getOperatorName(), loan.getLtd());
		ModelResult<Boolean> modelResult = o2oComBankFeeService.backFee(loan);
		logger.debug("start-up Technological process result params isSuccess:{},ErrCode:{},ErrMsg:{},etailStack:{}", modelResult.isSuccess(), modelResult.getErrCode(), modelResult.getErrMsg(), modelResult.getDetailStack());
		if (modelResult.isSuccess()) {
			String URL = " OL.BILLSTATUSOTF='" + StatusContexts.WFTYPE_STATUS_RUN + "' , OL.BILLSTATUSMANAGEOTF='" + StatusContexts.WFTYPE_STATUS_RUN + "' ";
			String updateSql = "UPDATE EADB.O2O_LOANAPPLY OL SET " + URL + " WHERE OL.BILLCODE=?";
			o2oComBankFeeService.updateBackFee(updateSql, billCode);
			// 流程启动后更新主表
			o2oComBankFeeService.updateWorkFlowStatus(StatusContexts.WFTYPE_STATUS_RUN, loan.getLoanapplyNo());
			return BaseRestResult.info("退费申请提交成功").andRefresh();
		}
		return BaseRestResult.warn(modelResult.getErrMsg());
	}

	/**
	 * 返回OA系统贷款主申请id
	 * 
	 * @param billCode
	 * @return
	 */
	public O2oLoanapplyEntity getOaLoanEntity(String billCode) {
		String sql = "SELECT OL.LOANAPPLYNO,OL.BILLCODE,OL.OPERATORNO,OL.OPERATORNAME,OL.LTD FROM EADB.O2O_LOANAPPLY OL WHERE OL.BILLCODE=?";
		List<Object[]> loans = o2oComBankFeeService.findBackFee(sql, billCode);
		O2oLoanapplyEntity loan = new O2oLoanapplyEntity();
		for (int k = 0; k < loans.size(); k++) {
			loan.setLoanapplyNo(loans.get(k)[0].toString());
			loan.setBillCode(loans.get(k)[1].toString());
			loan.setOperatorNo(loans.get(k)[2].toString());
			loan.setOperatorName(loans.get(k)[3].toString());
			loan.setLtd(loans.get(k)[4].toString());
		}
		return loan;
	}

	/**
	 * OA 退款
	 * 
	 * @param comBackFeeForm
	 *            更新退款实体信息
	 * @return
	 */
	@RequestMapping(value = "/oa_update")
	public BaseRestResult<String> oaUpdate(ComBackFeeForm comBackFeeForm) {
		if (StringUtil.isEmpty(comBackFeeForm.getLoanapplyNo())) {
			return BaseRestResult.warn("贷款单号不能为空");
		}
		if (null == comBackFeeForm.getRequiredDate()) {
			return BaseRestResult.warn("要求付款日期不能为空");
		}
		OaBackFeeEntity oaBackFeeEntity = getOaBackFeeEntity(comBackFeeForm.getLoanapplyNo());
		if (comBackFeeForm.getBackDeposite().compareTo(oaBackFeeEntity.getNotRetreatBond()) == 1) {
			return BaseRestResult.warn("应退保证金不能大于未退保证金");
		}
		if (comBackFeeForm.getBackManger().compareTo(oaBackFeeEntity.getNotRetreatFee()) == 1) {
			return BaseRestResult.warn("应退管理费不能大于未退管理费");
		}
		BigDecimal notRetreatRisk = oaBackFeeEntity.getNotRetreatRisk();
		if (notRetreatRisk == null) {
			notRetreatRisk = new BigDecimal(0.00);
		}
		if (comBackFeeForm.getBackRisk().compareTo(notRetreatRisk) == 1) {
			return BaseRestResult.warn("应退风险补偿金不能大于未退风险补偿金");
		}
		// 校验银行卡
		String isBankno = BankNoCheckUtil.checkBankNo(comBackFeeForm.getBankAccount());
		if (isBankno.equals(BankNoCheckUtil.IS1619)) {
			return BaseRestResult.warn("银行卡号须16到19之间");
		} else if (isBankno.equals(BankNoCheckUtil.ISNUMBER)) {
			return BaseRestResult.warn("银行卡号必须全为数字");
		} else if (isBankno.equals(BankNoCheckUtil.ISNOT)) {
			return BaseRestResult.warn("银行卡号不符合规范");
		}
		int i = o2oComBankFeeService.findOaBackFeeCount(comBackFeeForm.getLoanapplyNo());
		if (i == OaBackFeeStatus.BACK_COUNT) {// 保证金流程
			return BaseRestResult.warn("存在保证金管理费退费流程");
		}
		String sql = "SELECT OCB.BILL_STATUS FROM O2O_COM_BACKFEE OCB WHERE OCB.BILL_CODE = ?";
		String result = o2oComBankFeeService.findO2oString(sql, comBackFeeForm.getLoanapplyNo());
		if (StatusContexts.WFTYPE_STATUS_RUN.equals(result)) {
			return BaseRestResult.warn("存在保证金管理费退费流程");
		}
		// else if (i == OaBackFeeStatus.MANA_COUNT) {// 管理费流程
		// return BaseRestResult.warn("存在管理费退费流程");
		// } else if (i == OaBackFeeStatus.RISK_COUNT) {// 风险补偿金流程
		// return BaseRestResult.warn("存在风险补偿金退费流程");
		// }
		logger.debug("oa update back fee params:{}", comBackFeeForm);
		OaUpdateBackFeeEntity oaUp = new OaUpdateBackFeeEntity();
		oaUp.setBackBankAccount(comBackFeeForm.getBankAccount());
		oaUp.setBackBankAddr(comBackFeeForm.getBankAddr());
		oaUp.setBackBankName(comBackFeeForm.getBankName());
		oaUp.setBackPayDate(DateUtils.formateStandDate(comBackFeeForm.getRequiredDate()));
		oaUp.setBackPayMode(comBackFeeForm.getPayMode());
		oaUp.setBackPayType(comBackFeeForm.getPayType());
		oaUp.setBackPayRemark(comBackFeeForm.getPayRemark());
		oaUp.setBillCode(comBackFeeForm.getLoanapplyNo());
		oaUp.setBillStatuSotf(StatusContexts.WFTYPE_STATUS_NEW);
		oaUp.setBillStatusManageotf(StatusContexts.WFTYPE_STATUS_NEW);
		oaUp.setUnDeposit(comBackFeeForm.getBackDeposite());
		oaUp.setBackRisk(comBackFeeForm.getBackRisk());
		oaUp.setBackManger(comBackFeeForm.getBackManger());
		o2oComBankFeeService.updateOaBackFee(oaUp);

		// 新增一条数据
		O2OComBackFee o2OComBackFee = new O2OComBackFee();
		O2oComBackFeeTransFormart.fromToFee(o2OComBackFee, comBackFeeForm);
		o2OComBackFee.setAccountName(getOaBackFeeEntity(comBackFeeForm.getLoanapplyNo()).getUserName());
		o2OComBackFee.setDataSource(StatusContexts.DATA_SOURCE_OLD);
		o2OComBackFee.setLoanapplyNo(getOaLoanEntity(comBackFeeForm.getLoanapplyNo()).getLoanapplyNo());
		o2OComBackFee.setBillCode(comBackFeeForm.getLoanapplyNo());
		o2OComBackFee.setBillStatus(StatusContexts.WFTYPE_STATUS_NEW);
		if (StringUtil.isEmpty(result)) {
			o2oComBankFeeService.save(o2OComBackFee);
		} else {
			String sql_id = "SELECT OCB.ID FROM O2O_COM_BACKFEE OCB WHERE OCB.BILL_CODE = ?";
			o2OComBackFee.setId(o2oComBankFeeService.findO2oString(sql_id, comBackFeeForm.getLoanapplyNo()));
			o2oComBankFeeService.updateById(o2OComBackFee);
		}
		return BaseRestResult.info("保存成功");
	}

	/**
	 * 打印退款单
	 * 
	 * @param billCode
	 *            贷款编码
	 * @param printType
	 *            打印类型NEW-新系统，OLD-老系统
	 * @return
	 */
	@RequestMapping(value = "/print")
	public HtmlRestResult print(String billCode, String printType,String id) {
		// 审批详情
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 设置显示格式
		ViewContext.put("printDate", df.format(new Date()));
		if (StatusContexts.DATA_SOURCE_OLD.equals(printType)) {
			String agreeUrl = baseUtils.getApprovalAgreeUrl(getOaLoanEntity(billCode).getLoanapplyNo(), null, SystemModule.SYSTEM_MODULE_O2O);
			ViewContext.put("agreeUrl", agreeUrl);
			OaBackFeeEntity oaBackFeeEntity = getOaBackFeeEntity(billCode);
			ViewContext.put("vo", trans(billCode));
			ViewContext.put("backfee", oaBackFeeEntity);
		} else {
			O2oLoanapplyEntity loanapply = null;
			/*if (billCode.startsWith("O2O")) {
				OaBackFeeEntity oaBackFeeEntity = o2OComBankFeeService.findOaBackFee(billCode);
				loanapply = OaBackFeeTransO2Oloanapply.transO2oLoanapplyEntity(oaBackFeeEntity);
				log.info("续贷查询调用CRM方法开始，参数billCode:{}", billCode);
				com.eascs.crm.common.vo.ModelResult<String> modelResult = iCustomerInfoService.getCustomerByBillCode(billCode);
				log.info("调用CRM接口是否成功：{}", modelResult.isSuccess());
				if (modelResult.isSuccess()) {
					userNo = modelResult.getModel();
				} else {
					userNo = "";
				}
				loanapply.setLoanId(userNo);
			} else {*/
				loanapply = o2oLoanapplyService.fingByBillCode(billCode);
			//}
			
			QueryCustomerVO vo = new QueryCustomerVO();
			vo.setCustomer_id(loanapply.getLoanId());
			String agreeUrl = baseUtils.getApprovalAgreeUrl(loanapply.getLoanapplyNo(), null, SystemModule.SYSTEM_MODULE_O2O);
			ViewContext.put("agreeUrl", agreeUrl);
			CustomerView customer = iCustomerInfoService.geCustomerView(vo);
			//O2OComBackFee o2OComBackFee = o2oComBankFeeService.queryEntity(loanapply.getLoanapplyNo(), StatusContexts.WFTYPE_STATUS_NEW);
			O2OComBackFee o2OComBackFee = o2oComBankFeeService.queryById(id);
			ComBackFeeForm comBackFeeForm = new ComBackFeeForm();
			if (null != o2OComBackFee) {
				comBackFeeForm.setLoanapplyNo(loanapply.getBillCode());
				comBackFeeForm.setBackDeposite(o2OComBackFee.getBackDeposite());
				comBackFeeForm.setBackManger(o2OComBackFee.getBackManger());
				comBackFeeForm.setBackRisk(o2OComBackFee.getBackRisk());
				comBackFeeForm.setBankAccount(o2OComBackFee.getBankAccount());
				comBackFeeForm.setBankAddr(o2OComBackFee.getBankAddr());
				comBackFeeForm.setBankName(o2OComBackFee.getBankName());
				comBackFeeForm.setPayType(o2OComBackFee.getPayType());
				comBackFeeForm.setPayMode(o2OComBackFee.getPayMode());
				comBackFeeForm.setPayRemark(o2OComBackFee.getPayRemark());
				if (null != o2OComBackFee.getRequiredDate())
					comBackFeeForm.setRequiredDate(DateUtils.formateStandTime(o2OComBackFee.getRequiredDate()));
			}
			// 中间信息
			OaBackFeeEntity oaBackFeeEntity = new OaBackFeeEntity();
			oaBackFeeEntity.setCustermName(loanapply.getCustomeRname());
			oaBackFeeEntity.setBillCode(loanapply.getBillCode());
			oaBackFeeEntity.setNamecn(loanapply.getLtdName());
			List<String> payTypeList = Arrays.asList(o2OComBackFee.getPayType().split(","));
			ViewContext.put("payTypeList",payTypeList);
			/*if(billCode.startsWith("O2O")){
				OaBackFeeEntity oaBackFeeEntity1 = o2OComBankFeeService.findOaBackFee(billCode);
				CustomerBasicInfoEntity oaCustomerBasic = OaBackFeeTransO2Oloanapply.transCustomerBasicInfoEntity(oaBackFeeEntity1);
				oaBackFeeEntity.setUserName(oaCustomerBasic.getCustomerName());
			}else{*/
				if (null != customer.getBasicInfo()) {
					oaBackFeeEntity.setUserName(customer.getBasicInfo().getCustomerName());
				}
			//}
			ViewContext.put("vo", comBackFeeForm);
			ViewContext.put("backfee", oaBackFeeEntity);
		}
		return HtmlRestResult.popHtmlFragment("backfee/bond_print");
	}
	
	
	/**
	 * 打印收款收据（新系统数据）
	 * 
	 * @param billCode
	 *            贷款编码
	 * @return
	 */
	@RequestMapping(value = "/gatherPrint")
	public HtmlRestResult gatherPrint(String billCode, String printType) {
		// 审批详情
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 设置显示格式
		ViewContext.put("printDate", df.format(new Date()));
		if (StatusContexts.DATA_SOURCE_OLD.equals(printType)) {
			String agreeUrl = baseUtils.getApprovalAgreeUrl(getOaLoanEntity(billCode).getLoanapplyNo(), null, SystemModule.SYSTEM_MODULE_O2O);
			ViewContext.put("agreeUrl", agreeUrl);
			OaBackFeeEntity oaBackFeeEntity = getOaBackFeeEntity(billCode);
			ViewContext.put("vo", trans(billCode));
			ViewContext.put("backfee", oaBackFeeEntity);
		} else {
			O2oLoanapplyEntity loanapply = o2oLoanapplyService.fingByBillCode(billCode);
			QueryCustomerVO vo = new QueryCustomerVO();
			vo.setCustomer_id(loanapply.getLoanId());
			String agreeUrl = baseUtils.getApprovalAgreeUrl(loanapply.getLoanapplyNo(), null, SystemModule.SYSTEM_MODULE_O2O);
			ViewContext.put("agreeUrl", agreeUrl);
			CustomerView customer = iCustomerInfoService.geCustomerView(vo);
			O2OComReceiveFee o2OComReceiveFee = o2oComBankFeeService.queryReceiveEntity(loanapply.getLoanapplyNo(), StatusContexts.WFTYPE_STATUS_NEW);
			ComBackReceiveForm comBackReceiveForm = new ComBackReceiveForm();
			String bigModeRedDeposite=toBigMode(o2OComReceiveFee.getRedDeposite());
			ViewContext.put("bigModeRedDeposite", bigModeRedDeposite);
			String bigModeRedManger=toBigMode(o2OComReceiveFee.getRedManger());
			ViewContext.put("bigModeRedManger", bigModeRedManger);
			String bigModeRedRisk=toBigMode(o2OComReceiveFee.getRedRisk());
			ViewContext.put("bigModeRedRisk", bigModeRedRisk);
			if (null != o2OComReceiveFee) {
				comBackReceiveForm.setLoanapplyNo(loanapply.getBillCode());
				comBackReceiveForm.setPayName(o2OComReceiveFee.getPayName());
				comBackReceiveForm.setReceiveDeposite(o2OComReceiveFee.getRedDeposite());
				comBackReceiveForm.setReceiveManger(o2OComReceiveFee.getRedManger());
				comBackReceiveForm.setReceiveRisk(o2OComReceiveFee.getRedRisk());
				
				if (null != o2OComReceiveFee.getPayDate())
					comBackReceiveForm.setPayDate(DateUtils.formateStandTime(o2OComReceiveFee.getPayDate()));
			}
			// 中间信息
			OaBackFeeEntity oaBackFeeEntity = new OaBackFeeEntity();
			oaBackFeeEntity.setCustermName(loanapply.getCustomeRname());
			oaBackFeeEntity.setBillCode(loanapply.getBillCode());
			oaBackFeeEntity.setNamecn(loanapply.getLtdName());
			if (null != customer.getBasicInfo()) {
				oaBackFeeEntity.setUserName(customer.getBasicInfo().getCustomerName());
			}
			ViewContext.put("vo", comBackReceiveForm);
			ViewContext.put("backfee", oaBackFeeEntity);
		}
		return HtmlRestResult.popHtmlFragment("backfee/bond_gathering_print");
	}
	
	/**
	 * 打印收款收据（老系统数据）
	 * 
	 * @param billCode
	 *            贷款编码
	 * @return
	 */
	@RequestMapping(value = "/gatherPrintByOld")
	public HtmlRestResult gatherPrintByOld(String billCode) {
		// 审批详情
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 设置显示格式
		ViewContext.put("printDate", df.format(new Date()));

		OaBackFeeEntity oaBackFeeEntity = o2oComBankFeeService.findOaBackFeeByOld(billCode);
		ComBackReceiveByOldForm comBackReceiveByOldForm = new ComBackReceiveByOldForm();
		String bigModeRedDeposite = toBigMode2(oaBackFeeEntity.getNetReceiptsBond());
		ViewContext.put("bigModeRedDeposite", bigModeRedDeposite);
		String bigModeRedManger = toBigMode2(oaBackFeeEntity.getNetReceiptsFee());
		ViewContext.put("bigModeRedManger", bigModeRedManger);
		String bigModeRedRisk = toBigMode2(oaBackFeeEntity.getNetReceiptsRisk());
		ViewContext.put("bigModeRedRisk", bigModeRedRisk);
		if (null != oaBackFeeEntity) {
			comBackReceiveByOldForm.setBillCode(oaBackFeeEntity.getBillCode());
			comBackReceiveByOldForm.setPayName(oaBackFeeEntity.getUserName());
			comBackReceiveByOldForm.setReceiveDeposite(oaBackFeeEntity.getNetReceiptsBond());
			comBackReceiveByOldForm.setReceiveManger(oaBackFeeEntity.getNetReceiptsFee());
			comBackReceiveByOldForm.setReceiveRisk(oaBackFeeEntity.getNetReceiptsRisk());

			if (null != oaBackFeeEntity.getPaydate())
				comBackReceiveByOldForm.setPayDate(DateUtils.formateStandTime(oaBackFeeEntity.getPaydate()));
		}
		ViewContext.put("vo", comBackReceiveByOldForm);

		return HtmlRestResult.popHtmlFragment("backfee/bond_gathering_print_old");
	}
	
	/**
	 * 流程中审核的详情页面
	 * @param entityVo
	 * @return
	 */
	@SuppressWarnings("unused")
	@RequestMapping("/backfeeView")
	public BaseRestResult<String> backfeeView(O2oRepaymentRecordVo entityVo) {
		if("FINISH".equals(entityVo.getApprovalStatus()) || "PROCESSING".equals(entityVo.getApprovalStatus())){
			O2oLoanapplyEntity loanapply = null;
			/*if(entityVo.getBillCode().startsWith("O2O")){
				 loanapply = o2oLoanapplyService.fingByBillCode(entityVo.getBillCode());
			}else{*/
			loanapply = o2oLoanapplyService.fingByBillCode(entityVo.getBillCode());
			//OaBackFeeEntity oaBackFeeEntity = o2oComBankFeeService.findOaBackFee(entityVo.getBillCode());
			 //老系统中的应收，实收，已退，未退
			//OaBackFeeEntity oaBackFeeEntity = o2OComBankFeeService.findOaBackFeeById(comBackFeeForm.getLoanapplyNo());
			//loanapply = OaBackFeeTransO2Oloanapply.transO2oLoanapplyEntity(oaBackFeeEntity);
			//}
			
			LoanapplyExpand expand = loanapplyExpandService.queryLoanapplyNo(loanapply.getLoanapplyNo());
			O2oLoanUserEntity loanUser = o2oLoanUserService.findById(loanapply.getLoanId(), loanapply.getLoanapplyNo());
			List<O2OComBackFee> o2OComBackFeelist = o2oComBankFeeService.findEntitys(loanapply.getBillCode());
			O2oLoanUserEntity materEntity = o2oLoanUserService.findSpouseId(loanapply.getLoanId(), loanapply.getLoanapplyNo());
			ViewContext.put("o2OComBackFeelist", o2OComBackFeelist);
			FormBackFeeEntity entity = new FormBackFeeEntity();
			entity.setPageSize(10);
			entity.setBill_code(loanapply.getBillCode());
			String url = "/backfee/list";
			if (null != entity) {
				 String billCode = entity.getBill_code() == null ? "" : entity.getBill_code();
				url = UrlUtil.appendUrl(url, "billCode", loanapply.getBillCode());
				url = url + "&pageIndex=";
			} else {
				url = url + "?pageIndex=";
			}
			PageResult<Object[]> pageResult = o2oComBankFeeService.findByPageList(entity);
			SelectDataOption[] selectDataOptions = { null,  null, null, null, null, null,null,null,new SelectDataOption("BILLSTATUS") };
			String[] titles = { "单据号", "借款人姓名", "退费开户银行名称", "退费银行账", "退费账户户名", "退风险补偿金金额", "退管理费金额", "退保证金金额", "状态" };
			PaginationInfo paginationInfo = new PaginationInfo(pageResult, titles, url);
			paginationInfo.setBuildPagingNavigation(true);
			paginationInfo.setFirstRenderColumnIndex(1);
			paginationInfo.setSelectDataOptions(selectDataOptions);
			paginationInfo.setFormats(new Format[] { null, null,null,null,null, new DecimalFormat(",##0.00"),new DecimalFormat(",##0.00"), new DecimalFormat(",##0.00"), null });
			ViewContext.put("paginationInfo", paginationInfo);
			ViewContext.put("loanUser", loanUser);
			ViewContext.put("loanapply", loanapply);
			ViewContext.put("materEntity", materEntity);
			expand =o2oComBankFeeService.sumn(expand);
			ViewContext.put("loanapplyExpand", expand);
			String agreeUrl = baseUtils.getApprovalAgreeUrl(loanapply.getLoanapplyNo(), null, SystemModule.SYSTEM_MODULE_O2O);
			ViewContext.put("agreeUrl", agreeUrl);
			return HtmlRestResult.popHtmlFragment("backfee/backfee_detail");
		}
		String type = entityVo.getType();
		O2OComBackFee o2OComBackFee = null;
		String billCode = null;
		if(type==null&&entityVo.getReferId()!=null){ //如果type没有值说明是查看
			o2OComBackFee = o2oComBankFeeService.queryById(entityVo.getReferId());
			 billCode = o2OComBackFee.getBillCode();
		}else{
			billCode = entityVo.getBillCode();
			O2oLoanapplyEntity loanapply = null;
			
			/*if(billCode.startsWith("O2O")){
				OaBackFeeEntity oaBackFeeEntity = o2oComBankFeeService.findOaBackFee(billCode);
				loanapply = OaBackFeeTransO2Oloanapply.transO2oLoanapplyEntity(oaBackFeeEntity);
			}else{*/
				loanapply = o2oLoanapplyService.fingByBillCode(billCode);
			//}
			o2OComBackFee = o2oComBankFeeService.queryEntity(loanapply.getLoanapplyNo(), StatusContexts.WFTYPE_STATUS_RUN);
		}
		ViewContext.put("type", type);
		if(type!=null && type.equals("1")){
			String approvalUrl = baseUtils.getApprovalUrl(entityVo.getNodeAuditorId(), ProcessTemplate.SYSTEM_MODULE_O2O);// 审批代办列表详情URL
			ViewContext.put("approvalUrl", approvalUrl);
		}else
		{
			String agreeUrl = baseUtils.getApprovalAgreeUrl(o2OComBackFee.getLoanapplyNo(), null, SystemModule.SYSTEM_MODULE_O2O);
			ViewContext.put("agreeUrl", agreeUrl);
		}
		log.info("工作流访问回款详情：参数billCode：【{}】", billCode);
		// 退费详细信息
		//如果是老系统的数据
		O2oLoanapplyEntity loanapply = null;
		LoanapplyExpand loanapplyExpand = null;
		CustomerView customer = null;
		/*if(o2OComBackFee.getDataSource().equals(StatusContexts.DATA_SOURCE_OLD)){
			OaBackFeeEntity oaBackFeeEntity = o2oComBankFeeService.findOaBackFee(billCode);
			 //老系统中的应收，实收，已退，未退
			//OaBackFeeEntity oaBackFeeEntity = o2OComBankFeeService.findOaBackFeeById(comBackFeeForm.getLoanapplyNo());
			 loanapplyExpand= OaBackFeeTransO2Oloanapply.transloanapplyExpand(oaBackFeeEntity);
			 loanapplyExpand.setBillStatus(StatusContexts.WFTYPE_STATUS_CLO);
			 loanapply = OaBackFeeTransO2Oloanapply.transO2oLoanapplyEntity(oaBackFeeEntity);
			 customer = new CustomerView();
			 //basicInfo
			 CustomerBasicInfoEntity basicInfo =OaBackFeeTransO2Oloanapply.transCustomerBasicInfoEntity(oaBackFeeEntity);
			 customer.setBasicInfo(basicInfo);
		}else{*/
			 loanapply = o2oLoanapplyService.fingByBillCode(billCode);
			 loanapplyExpand = loanapplyExpandService.queryLoanapplyNo(loanapply.getLoanapplyNo());
			 QueryCustomerVO vo = new QueryCustomerVO();
			 vo.setCustomer_id(loanapply.getLoanId());
			 customer = iCustomerInfoService.geCustomerView(vo);
			 O2oLoanUserEntity materEntity = o2oLoanUserService.findSpouseId(loanapply.getLoanId(), loanapply.getLoanapplyNo());
		//}
		if (loanapplyExpand.getBillStatus().equals(StatusContexts.WFTYPE_STATUS_CLO)) {
			
			Button button = ButtonHelper.createAjaxButton("启动流程", "/combackfeesubmit/backfeestartup?referId=" + entityVo.getReferId());
			button.setPermissionCode("tbzjglfStartFlowButton");
			ViewContext.put("button", button);
			
			// 中间信息
			List<O2OComBackFee> o2OComBackFeelist = o2oComBankFeeService.findEntitys(loanapply.getBillCode());
			ViewContext.put("o2OComBackFeelist", o2OComBackFeelist);
			FormBackFeeEntity entity = new FormBackFeeEntity();
			entity.setPageSize(10);
			entity.setBill_code(billCode);
			String url = "/backfee/list";
			if (null != entity) {
				 billCode = entity.getBill_code() == null ? "" : entity.getBill_code();
				url = UrlUtil.appendUrl(url, "billCode", billCode);
				url = url + "&pageIndex=";
			} else {
				url = url + "?pageIndex=";
			}
			PageResult<Object[]> pageResult = o2oComBankFeeService.findByPageList(entity);
			SelectDataOption[] selectDataOptions = { null,  null, null, null, null, null,null,null,new SelectDataOption("BILLSTATUS") };
			String[] titles = { "单据号", "借款人姓名", "退费开户银行名称", "退费银行账", "退费账户户名", "退风险补偿金金额", "退管理费金额", "退保证金金额", "状态" };
			PaginationInfo paginationInfo = new PaginationInfo(pageResult, titles, url);
			paginationInfo.setBuildPagingNavigation(true);
			paginationInfo.setFirstRenderColumnIndex(1);
			paginationInfo.setSelectDataOptions(selectDataOptions);
			paginationInfo.setFormats(new Format[] { null,null,null,null,null, new DecimalFormat(",##0.00"),new DecimalFormat(",##0.00"), new DecimalFormat(",##0.00"), null });
			ViewContext.put("paginationInfo", paginationInfo);
			loanapplyExpand =o2oComBankFeeService.sumn(loanapplyExpand);
			ViewContext.put("comBackFeeForm", o2OComBackFee);
			ViewContext.put("loanapply", loanapply);
			ViewContext.put("materEntity", materEntity);
			ViewContext.put("loanapplyExpand", loanapplyExpand);
			ViewContext.put("basic", customer.getBasicInfo());
			if(o2OComBackFee!=null){
				 List<String> payTypeList = Arrays.asList(o2OComBackFee.getPayType().split(","));
					ViewContext.put("payTypeList",payTypeList);
			}
			return HtmlRestResult.popHtmlFragment("approval/backfee_approval");
		} else if (loanapplyExpand.getBillStatus().equals(StatusContexts.BZJ_STATUS_NEW)) {
			return BaseRestResult.warn("未缴纳保证金管理费。");
		} else {
			return BaseRestResult.warn("保证金管理费流程还未结束，无法退费。");
		}
	}
	
	/** 
	 * 采用分段的方式将给定小写金额转换成中文大写形式<br/> 
	 * 从小数点开始向前数，四位为一段<br/> 
	 * 支持整数位最多13位、小数位最多2位，多于两位的小数会被忽略<br/> 
	 *  
	 * @param value 
	 *            小写金额 
	 * @return 转换后的中文大写字符串 
	 */  
	public static String toBigMode(double value)  
	{  
	    final char[] NUMBER_CHAR = "零壹贰叁肆伍陆柒捌玖".toCharArray(); // 大写数字  
	    final String[] IN_UNIT_CHAR = { "", "拾", "佰", "仟" }; // 段内字符  
	    final String[] UNIT_NAME = { "", "万", "亿", "万亿" }; // 段名  
	  
	    // 金额乘100并转换成整数字符串（取出元角分数值）  
	    String valStr = new BigDecimal(Double.toString(value)).multiply(  
	            new BigDecimal("100")).toString();  
	    if(valStr.indexOf(".") > 0)  
	    {  
	        valStr = valStr.substring(0, valStr.indexOf("."));  
	    }  
	  
	    StringBuilder prefix = new StringBuilder(); // 整数部分转化的结果  
	    StringBuilder suffix = new StringBuilder(); // 小数部分转化的结果  
	  
	    if (valStr.length() <= 2) // 只有小数部分  
	    {  
	        prefix.append("零万零千零佰零拾零元");  
	        if (valStr.equals("0"))  
	        {  
	            suffix.append("零角零分");  
	        } else if (valStr.length() == 1)  
	        {  
	            suffix.append(NUMBER_CHAR[valStr.charAt(0) - '0']).append("分");  
	        } else  
	        {  
	            suffix.append(NUMBER_CHAR[valStr.charAt(0) - '0']).append("角");  
	            suffix.append(NUMBER_CHAR[valStr.charAt(1) - '0']).append("分");  
	        }  
	    } else  
	    {  
	        int flag = valStr.length() - 2;  
	        String head = valStr.substring(0, flag); // 取整数部分  
	        String rail = valStr.substring(flag); // 取小数部分  
	  
	        if (head.length() > 13)  
	        {  
	            return "数值太大(最大支持13位整数)，无法处理。";  
	        }  
	  
	        // 处理整数位  
	        char[] ch = head.toCharArray();  
	        int zeroNum = 0; // 连续零的个数  
	        for (int i = 0; i < ch.length; i++)  
	        {  
	            int index = (ch.length - i - 1) % 4; // 取段内位置，介于 3 2 1 0  
	            int indexLoc = (ch.length - i - 1) / 4; // 取段位置，介于 3 2 1 0  
	  
	            
	            if (ch[i] == '0')  
	            {  
	            	prefix.append("零");
	            	prefix.append(IN_UNIT_CHAR[index]); // 添加段内标识
	            } else  
	            {  
	                if (zeroNum != 0)  
	                {  
	                    if (index != 3)  
	                    {  
	                        prefix.append("零");  
	                    }  
	                    zeroNum = 0;  
	                }  
	                prefix.append(NUMBER_CHAR[ch[i] - '0']); // 转换该位置的数  
	  
	                prefix.append(IN_UNIT_CHAR[index]); // 添加段内标识  
	            }  
	  
	            if (index == 0 && zeroNum < 4) // 添加段名  
	            {  
	                prefix.append(UNIT_NAME[indexLoc]);  
	            }  
	        }  
	        prefix.append("元");  
	        
	        if (prefix.length()==8)  
            {  
                 prefix.insert(0,"零万");  
            }else 
           	if (prefix.length()==6)  
            {  
                 prefix.insert(0,"零万零仟");  
            }else
           	if (prefix.length()==4)  
            {  
                 prefix.insert(0,"零万零仟零佰零拾");  
            }
	        
	        // 处理小数位  
	        if (rail.equals("00"))  
	        {  
	            suffix.append("零角零分");  
	        } else if (rail.startsWith("0"))  
	        {  
	            suffix.append(NUMBER_CHAR[rail.charAt(1) - '0']).append("分");  
	        } else  
	        {  
	            suffix.append(NUMBER_CHAR[rail.charAt(0) - '0']).append("角");  
	            suffix.append(NUMBER_CHAR[rail.charAt(1) - '0']).append("分");  
	        }  
	    }  
	    
	    
	    return prefix.append(suffix).toString();  
	}
	
	public static String toBigMode2(BigDecimal value)  
	{  
	    final char[] NUMBER_CHAR = "零壹贰叁肆伍陆柒捌玖".toCharArray(); // 大写数字  
	    final String[] IN_UNIT_CHAR = { "", "拾", "佰", "仟" }; // 段内字符  
	    final String[] UNIT_NAME = { "", "万", "亿", "万亿" }; // 段名  
	  
	    // 金额乘100并转换成整数字符串（取出元角分数值）  
	    String valStr = value.multiply(  
	            new BigDecimal("100")).toString();  
	    if(valStr.indexOf(".") > 0)  
	    {  
	        valStr = valStr.substring(0, valStr.indexOf("."));  
	    }  
	  
	    StringBuilder prefix = new StringBuilder(); // 整数部分转化的结果  
	    StringBuilder suffix = new StringBuilder(); // 小数部分转化的结果  
	  
	    if (valStr.length() <= 2) // 只有小数部分  
	    {  
	        prefix.append("零万零千零佰零拾零元");  
	        if (valStr.equals("0"))  
	        {  
	            suffix.append("零角零分");  
	        } else if (valStr.length() == 1)  
	        {  
	            suffix.append(NUMBER_CHAR[valStr.charAt(0) - '0']).append("分");  
	        } else  
	        {  
	            suffix.append(NUMBER_CHAR[valStr.charAt(0) - '0']).append("角");  
	            suffix.append(NUMBER_CHAR[valStr.charAt(1) - '0']).append("分");  
	        }  
	    } else  
	    {  
	        int flag = valStr.length() - 2;  
	        String head = valStr.substring(0, flag); // 取整数部分  
	        String rail = valStr.substring(flag); // 取小数部分  
	  
	        if (head.length() > 13)  
	        {  
	            return "数值太大(最大支持13位整数)，无法处理。";  
	        }  
	  
	        // 处理整数位  
	        char[] ch = head.toCharArray();  
	        int zeroNum = 0; // 连续零的个数  
	        for (int i = 0; i < ch.length; i++)  
	        {  
	            int index = (ch.length - i - 1) % 4; // 取段内位置，介于 3 2 1 0  
	            int indexLoc = (ch.length - i - 1) / 4; // 取段位置，介于 3 2 1 0  
	  
	            
	            if (ch[i] == '0')  
	            {  
	            	prefix.append("零");
	            	prefix.append(IN_UNIT_CHAR[index]); // 添加段内标识
	            } else  
	            {  
	                if (zeroNum != 0)  
	                {  
	                    if (index != 3)  
	                    {  
	                        prefix.append("零");  
	                    }  
	                    zeroNum = 0;  
	                }  
	                prefix.append(NUMBER_CHAR[ch[i] - '0']); // 转换该位置的数  
	  
	                prefix.append(IN_UNIT_CHAR[index]); // 添加段内标识  
	            }  
	  
	            if (index == 0 && zeroNum < 4) // 添加段名  
	            {  
	                prefix.append(UNIT_NAME[indexLoc]);  
	            }  
	        }  
	        prefix.append("元");  
	        
	        if (prefix.length()==8)  
            {  
                 prefix.insert(0,"零万");  
            }else 
           	if (prefix.length()==6)  
            {  
                 prefix.insert(0,"零万零仟");  
            }else
           	if (prefix.length()==4)  
            {  
                 prefix.insert(0,"零万零仟零佰零拾");  
            }
	        
	        // 处理小数位  
	        if (rail.equals("00"))  
	        {  
	            suffix.append("零角零分");  
	        } else if (rail.startsWith("0"))  
	        {  
	            suffix.append(NUMBER_CHAR[rail.charAt(1) - '0']).append("分");  
	        } else  
	        {  
	            suffix.append(NUMBER_CHAR[rail.charAt(0) - '0']).append("角");  
	            suffix.append(NUMBER_CHAR[rail.charAt(1) - '0']).append("分");  
	        }  
	    }  
	    
	    
	    return prefix.append(suffix).toString();  
	}
	
	/**
	 * yy 收保证金管理费，代办页面 历史收退费情况记录(一个单一笔记录)
	 * @return
	 */
	@RequestMapping("/o2oDBbackfee")
	public PaginationRestResult getDBO2oBasicData(String loanId,String loanapplyNo) {
		// @o2o
		O2oLoanUserEntity materEntity = o2oLoanUserService.findSpouseId(loanId, loanapplyNo);
		PageResult<Object[]> o2opageResult =null;
		if(materEntity==null){
			o2opageResult = o2oComBankFeeService.findDBByPage( loanId, "");
		}else{
			o2opageResult = o2oComBankFeeService.findDBByPage( loanId, materEntity.getLoanId());
		}
		String[] o2otitles = { "内审单号", "借款人姓名", "已交保证金(元)", "已退保证金(元)", "未退保证金(元)" };
		
		PaginationInfo paginationInfo = new PaginationInfo(o2opageResult, o2otitles);
		paginationInfo.setBuildPagingNavigation(false);
		paginationInfo.setFirstRenderColumnIndex(0);
		//Button shenqign = ButtonHelper.createAjaxButton("申请退费", "/rbackfee/o2o_edit_oabond?billCode=");
		//Button gatherPrint = ButtonHelper.createAjaxButton("打印收款收据", "/rbackfee/gatherPrint?printType=NEW&billCode=");
		//shenqign.setShowButtonFilter(showBottun);
		//shenqign.setPermissionCode("refundApply");
		//gatherPrint.setPermissionCode("gatherPrint");
		Button detail = ButtonHelper.createAjaxButton(null, "/rbackfee/detail?billCode=");
		//Button[] findButton = new Button[] { shenqign,gatherPrint };
		Button[]  titleButtons= new Button[] { detail};
		paginationInfo.setFormats(new Format[] { null, null, new DecimalFormat(",##0.00"), new DecimalFormat(",##0.00"), new DecimalFormat(",##0.00") });
		//paginationInfo.setMoreButtons(findButton);
		paginationInfo.setTitleButtons(titleButtons);
		paginationInfo.setRendTo("#o2o_DBresult");
		//ViewContext.put("vo", entity);
		return PaginationRestResult.buildPaginationRestResult(paginationInfo);
	}
	
}
